package com.cqq.print.business.controller.produce;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.cqq.attachment.service.AttachmentService;
import com.cqq.attachment.service.bean.AttachmentBean;
import com.cqq.attachment.service.exception.AttachmentException;
import com.cqq.auth.service.UserService;
import com.cqq.auth.service.bean.UserBean;
import com.cqq.auth.service.bean.UserQueryBean;
import com.cqq.base.filter.FMContext;
import com.cqq.common.core.base.BaseController;
import com.cqq.common.core.bean.PageInfoBean;
import com.cqq.print.base.service.PProducePlanService;
import com.cqq.print.base.service.bean.PProducePlanBean;
import com.cqq.print.business.service.PCptProcessService;
import com.cqq.print.business.service.POcpProcessService;
import com.cqq.print.business.service.POrderService;
import com.cqq.print.business.service.PProduceDetailService;
import com.cqq.print.business.service.PProduceService;
import com.cqq.print.business.service.bean.PCptProcessBean;
import com.cqq.print.business.service.bean.POcpProcessBean;
import com.cqq.print.business.service.bean.POrderBean;
import com.cqq.print.business.service.bean.PProduceBean;
import com.cqq.print.business.service.bean.PProduceDetailBean;
import com.cqq.print.constant.Constant;
import com.cqq.pro.down.ImagePageController;
import com.cqq.pro.util.DateUtil;
import com.cqq.pro.util.PropertiesUtil;
import com.cqq.pro.util.ResponseUtil;

/**
 * 2015/06/25
 *
 * @author chenqq
 */
@Controller(value = "produceController")
@RequestMapping(value = { "produce" }, method = {
		RequestMethod.POST,
		RequestMethod.GET })
public class ProduceController extends BaseController{

	@Autowired
	private PProduceService pProduceService;
	@Autowired
	private PProduceDetailService pProduceDetailService;
	@Autowired
	private POrderService pOrderService;
	@Autowired
	private UserService userService;
	@Autowired
	private PProducePlanService pProducePlanService;
	@Autowired
	private PCptProcessService pCptProcessService;
	@Autowired
	private POcpProcessService pOcpProcessService;
	@Autowired
	private AttachmentService attachmentService;
	
	
	@RequestMapping(value = { "listAjax" }, method = {
			RequestMethod.GET,
			RequestMethod.POST })
	public String toListAjax(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		String name = request.getParameter("name");		
		String orderNum = request.getParameter("orderNum");		
		String status = request.getParameter("status");
		String checkStatus = request.getParameter("checkStatus");
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		Map<String,Object> map = new HashMap<String, Object>();
		
		if(name!=null&&!name.trim().equals("")){
			name = URLDecoder.decode(name, "utf-8");
			map.put("name", name);
		}
		if(orderNum!=null&&orderNum.trim().length()>0){
			map.put("orderNum",orderNum);
		}
		if(status!=null&&status.trim().length()>0&&Integer.parseInt(status)>=0){
			map.put("status",Integer.parseInt(status));
		}
		if(checkStatus!=null&&checkStatus.trim().length()>0&&Integer.parseInt(checkStatus)>=0){
			map.put("checkStatus",Integer.parseInt(checkStatus));
		}
		if(currentPage==null||currentPage.trim().length()<1){
			currentPage = "1";
		}
		if(pageSize==null||pageSize.trim().length()<1){
			pageSize = "20";
		}
		
		if(startDate==null||StringUtils.isEmpty(startDate))
		    startDate = DateUtil.formatDate(DateUtil.getFirstDateOfCurrentMonth());
		if(endDate==null||StringUtils.isEmpty(endDate))
			endDate = DateUtil.getCurrDateAfterAddDays(1);
		else
			endDate = DateUtil.addDaysForDate(endDate,1);
		
		map.put("startDate", startDate+" 00:00:00");
		map.put("endDate", endDate+" 00:00:00");
		
		int offset = (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize);
		map.put("orderClause", "create_date desc");
		map.put("pageSize", Integer.parseInt(pageSize));
		map.put("offset", offset);
		map.put("userId", FMContext.getCurrent().getUserId());
		
		PageInfoBean<PProduceBean> page = pProduceService.queryPageProduces(map);
		page.setPageNo(Integer.parseInt(currentPage));
		page.setPageSize(Integer.parseInt(pageSize));
		out.put("page", page);
		
		
		
		return "produce/producemanager";
		
	}
	
	
	@RequestMapping("toAddProduce")
	public String toAddProduce(Integer orderId, ModelMap out)  {
		if(orderId!=null){
			POrderBean poBean = pOrderService.queryOrderById(orderId);
			out.put("poBean", poBean);
		}
		return "produce/addProduce";
	}
	
	@RequestMapping("toEditProduce")
	public String toEditProduce(HttpServletRequest request, ModelMap out) {
		String produceId = request.getParameter("produceId");
		if(produceId!=null&&produceId.trim().length()>0){
			PProduceBean ppBean = pProduceService.queryProduceById(Integer.parseInt(produceId));
			out.put("ppBean", ppBean);
		}
		
		return "produce/editProduce";
	}
	
	@RequestMapping("toAddProduceDetail")
	public String toAddProduceDetail(HttpServletRequest request, ModelMap out) {
		try {
			String produceId = request.getParameter("produceId");
			if(produceId==null || produceId.trim().length()<1){
				produceId = "0";
			}
			PProduceBean ppBean = pProduceService.queryProduceById(Integer.parseInt(produceId));
			
			POrderBean poBean = pOrderService.queryOrderByorderNum(ppBean.getOrderNum());
			
			//订单明细信息
			List<PProduceDetailBean> listDetailBean = pProduceDetailService.queryDetailsByProduceId(Integer.parseInt(produceId));
			ppBean.setDetailCount(listDetailBean!=null?listDetailBean.size():0);
			
			//生产项
			List<PProducePlanBean> listPPPBean = pProducePlanService.queryByType(poBean.getOrderType());
			
			//生产者
			UserQueryBean userQueryBean = new UserQueryBean();
			userQueryBean.setNeedPaging(false);
			List<UserBean> listUserBean = userService.queryUserByPage(userQueryBean).getData();
			//附件
			List<AttachmentBean> listAttaBean = null;
			if(ppBean.getAttachmentIds()!=null){
				listAttaBean = attachmentService.queryAttachmentBeansByIds(ppBean.getAttachmentIds());
			}
			
			out.put("listPPPBean", listPPPBean);
			out.put("listUserBean", listUserBean);
			out.put("ppBean", ppBean);
			out.put("listDetailBean", listDetailBean);
			out.put("listAttaBean", listAttaBean);
		} catch (AttachmentException e) {
			log.error(e.getMessage());
		}
		return "produce/addProduceDetail";
	}
	
	@RequestMapping("loadProPlanAndUser")
	public String loadProPlanAndUser(Integer produceId, ModelMap out) {
		
		PProduceBean ppBean = pProduceService.queryProduceById(produceId);
		
		POrderBean poBean = pOrderService.queryOrderByorderNum(ppBean.getOrderNum());
		//生产项
		List<PProducePlanBean> listPPPBean = pProducePlanService.queryByType(poBean.getOrderType());
		//生产者
		UserQueryBean userQueryBean = new UserQueryBean();
		userQueryBean.setNeedPaging(false);
		List<UserBean> listUserBean = userService.queryUserByPage(userQueryBean).getData();
		
		out.put("listPPPBean", listPPPBean);
		out.put("listUserBean", listUserBean);
		
		return "produce/addProduceDetail-temp";
	}
	
	@RequestMapping("deleteProduce")
	public void deleteProduce(HttpServletRequest request,HttpServletResponse response){
		JSONObject json =  new JSONObject();
		String id = request.getParameter("produceId");
		if(id!=null&&id.trim().length()>0){
			try{				
				pProduceService.deleteProduce(Integer.parseInt(id));
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "producetId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("submitPProduce")
	public void submitPProduce(PProduceBean pProduceBean, HttpServletRequest request,HttpServletResponse response){
		//生产单信息
		JSONObject json = new JSONObject();
		try{
			Date currDate = new Date();
			pProduceBean.setUpdateDate(currDate);
			Integer produceId = pProduceBean.getId();
			if(pProduceBean.getId()==null||pProduceBean.getId()<1){
				POrderBean tempOrder = pOrderService.queryOrderByorderNum(pProduceBean.getOrderNum());
				if(tempOrder!=null){
					pProduceBean.setCreateDate(currDate);
					pProduceBean.setCreateId(FMContext.getCurrent().getUserId());
					produceId = pProduceService.insertSelective(pProduceBean);
					//更新订单的调度状态
					POrderBean pOrderBean = new POrderBean();
					pOrderBean.setId(tempOrder.getId());
					pOrderBean.setStatus(Constant.ORDER_STATUS_DISPATCH);
					pOrderService.updateStatus(pOrderBean);
				}
			}else{
				pProduceService.updateByPrimaryKey(pProduceBean);
			}
			json.put("result", "success");
			json.put("produceId", produceId);
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("updateCheckStatus")
	public void updateCheckStatus(HttpServletRequest request,HttpServletResponse response) {
		JSONObject json =  new JSONObject();
		String id = request.getParameter("produceId");
		if(id!=null&&id.trim().length()>0){
			try{				
				PProduceBean ppBean = new PProduceBean();
				ppBean.setId(Integer.parseInt(id));
				ppBean.setCheckStatus(Constant.PRODUCE_CHECKSTATUS_DONE);
				pProduceService.updateCheckStatus(ppBean);
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "producetId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("submitPProduceDetail")
	public void submitPProduceDetail(PProduceDetailBean pProduceDetailBean, HttpServletRequest request,HttpServletResponse response) {
		//生产任务明细信息
		JSONObject json = new JSONObject();
		try{
			pProduceDetailBean.setStartTime(DateUtil.formateStrToTDate(pProduceDetailBean.getStartDate()));
			pProduceDetailBean.setEndTime(DateUtil.formateStrToTDate(pProduceDetailBean.getEndDate()));
			pProduceDetailService.insertSelect(pProduceDetailBean);
			
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("loadCPTItems")
	public String loadCPTItems(HttpServletRequest request, ModelMap out){
		String proId = request.getParameter("proId");
		PCptProcessBean cptBean = null;
		if(proId!=null&&proId.trim().length()>0){
			cptBean = pCptProcessService.queryCPTProcessByProId(Integer.parseInt(proId));
		}
		if(cptBean==null)
			cptBean = new PCptProcessBean();
		out.put("cptBean", cptBean);
		return "produce/cptProcess";
	}
	
	@RequestMapping("loadOCTItems")
	public String loadOCTItems(HttpServletRequest request, ModelMap out){
		String proId = request.getParameter("proId");
		POcpProcessBean octBean = null;
		if(proId!=null&&proId.trim().length()>0){
			octBean = pOcpProcessService.queryOCPProcessByProId(Integer.parseInt(proId));
		}
		if(octBean==null)
			octBean = new POcpProcessBean();
		out.put("octBean", octBean);
		return "produce/octProcess";
	}
	
	@RequestMapping("savePCPTProcess")
	public void savePCPTProcess(PCptProcessBean cptBean,HttpServletResponse response) {
		//保存CPT流程
		JSONObject json = new JSONObject();
		try{
			pCptProcessService.savePCPTProcess(cptBean);
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("savePOCTProcess")
	public void savePOCTProcess(POcpProcessBean octBean,HttpServletResponse response) {
		//保存OCT流程
		JSONObject json = new JSONObject();
		try{
			pOcpProcessService.savePOCPProcess(octBean);
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("deleteProduceDetail")
	public void deleteProduceDetail(HttpServletRequest request,HttpServletResponse response){
		JSONObject json =  new JSONObject();
		String detailId = request.getParameter("produceDetailId");
		if(detailId!=null&&detailId.trim().length()>0){
			try{				
				pProduceDetailService.deleteById(Integer.parseInt(detailId));
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "producetId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	
	@RequestMapping("updateStatus")
	public void updateStatus(Integer produceId,Integer status, HttpServletResponse response) {
		JSONObject json =  new JSONObject();
		if(produceId!=null){
			try{				
				PProduceBean ppBean = pProduceService.queryProduceById(produceId);
				POrderBean tempOrder = pOrderService.queryOrderByorderNum(ppBean.getOrderNum());
				if(tempOrder!=null){
					ppBean.setStatus(status);
					ppBean.setUpdateDate(new Date());
					pProduceService.updateByPrimaryKey(ppBean);
					//更新订单的调度状态
					POrderBean pOrderBean = new POrderBean();
					pOrderBean.setId(tempOrder.getId());
					pOrderBean.setStatus(getOrderStatusByProduceStatus(status));
					pOrderService.updateStatus(pOrderBean);
				}
				
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "producetId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	private Integer getOrderStatusByProduceStatus(Integer status){
		Integer temp = Constant.ORDER_STATUS_DISPATCH;
		if(status.equals(Constant.PRODUCE_STATUS_ACCEPT))
			temp=Constant.ORDER_STATUS_ACCEPT;
		return temp;
	}
	
	
	/*==========================================生产明细===============================================*/
	
	@RequestMapping(value = { "listDetailAjax" }, method = {
			RequestMethod.GET,
			RequestMethod.POST })
	public String toListDetailAjax(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		String name = request.getParameter("name");		
		String orderNum = request.getParameter("orderNum");		
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		Map<String,Object> map = new HashMap<String, Object>();
		if(name!=null&&!name.trim().equals("")){
			name = URLDecoder.decode(name, "utf-8");
			map.put("name", name);
		}
		if(orderNum!=null&&orderNum.trim().length()>0){
			map.put("orderNum",orderNum);
		}
		if(currentPage==null||currentPage.trim().length()<1||Integer.parseInt(currentPage)<=0){
			currentPage = "1";
		}
		if(pageSize==null||pageSize.trim().length()<1){
			pageSize = "20";
		}
		
		int offset = (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize);
		map.put("pageSize", Integer.parseInt(pageSize));
		map.put("offset", offset);
		map.put("userId", FMContext.getLoginUser().getId());
		
		PageInfoBean<PProduceDetailBean> page = pProduceDetailService.queryDetailsByUserId(map);
		page.setPageNo(Integer.parseInt(currentPage));
		page.setPageSize(Integer.parseInt(pageSize));
		//生产项
		List<PProducePlanBean> listPPPBean = pProducePlanService.queryAll();
		out.put("page", page);
		out.put("listPPPBean", listPPPBean);
		return "produce/producemanagerDetail";
		
	}
	
	@RequestMapping("toShowProduceDetail")
	public String toShowProduceDetail(Integer id , ModelMap out){
		try {
		//查询子任务信息
		PProduceDetailBean detailBean = pProduceDetailService.findById(id);
		//查询任务信息
		PProduceBean produceBean = pProduceService.queryProduceById(detailBean.getProId());
		POrderBean pOrderBean = pOrderService.queryOrderByorderNum(produceBean.getOrderNum());
		//生产项
		List<PProducePlanBean> listPPPBean = pProducePlanService.queryByType(pOrderBean.getOrderType());
		//附件
		List<AttachmentBean> listAttaBean = null;
		if(produceBean.getAttachmentIds()!=null){
			listAttaBean = attachmentService.queryAttachmentBeansByIds(produceBean.getAttachmentIds());
		}
		out.put("detailBean", detailBean);
		out.put("produceBean", produceBean);
		out.put("listPPPBean", listPPPBean);
		out.put("listAttaBean", listAttaBean);
		} catch (AttachmentException e) {
			log.error(e.getMessage());
		}
		return "produce/produceDetailInfo";
	}
	
	
	@RequestMapping("savePProduceDetail")
	public void savetPProduceDetail(PProduceDetailBean pProduceDetailBean, HttpServletRequest request,HttpServletResponse response) {
		//生产任务明细信息
		JSONObject json = new JSONObject();
		try{
			pProduceDetailBean.setRealStartTime(DateUtil.formateStrToTDate(pProduceDetailBean.getRealStartDate()));
			pProduceDetailBean.setRealEndTime(DateUtil.formateStrToTDate(pProduceDetailBean.getRealEndDate()));
			pProduceDetailBean.setStatus(Constant.PRODUCE_DETAIL_STATUS_DONE);
			pProduceDetailService.updateByPrimaryKey(pProduceDetailBean);
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("saveProduceAttachment")
	public void saveProduceAttachment(PProduceBean produceBean,HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try{
			PProduceBean  temp = pProduceService.queryProduceById(produceBean.getId());
			Set<Integer> set = new HashSet<Integer>();
			setAttachmentId(set,produceBean.getAttachmentIds());
			setAttachmentId(set,temp.getAttachmentIds());
			produceBean.setAttachmentIds(set.toArray(new Integer[]{}));
			pProduceService.updateByPrimaryKey(produceBean);
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	protected void setAttachmentId(Set<Integer> set, Integer[] attachmentIds){
		if(attachmentIds==null||attachmentIds.length<1)
			return;
		for (Integer temp : attachmentIds) {
			set.add(temp);
		}
	}
	
	@RequestMapping(value = { "downloadAttachment" }, method = {
			RequestMethod.GET,
			RequestMethod.POST })
	public void downloadAttachment(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		try {
			String id = request.getParameter("id");
			log.info("in Download........zip.......id:" + id);
			AttachmentBean attachmentBean = attachmentService.selectByPrimaryKey(Integer.parseInt(id));
			InputStream io = new FileInputStream(PropertiesUtil.getConfigValue("file_path") + attachmentBean.getFilePath() + "/" + attachmentBean.getFileName());
			ImagePageController.download(response, io, attachmentBean.getOriginFileName());
			log.info("Download success...............");

		} catch (Exception e) {
			log.info(e.getMessage(), e);
		}
	}
}
